package com.gomcarter.frameworks.xmlexcel.upload;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.gomcarter.frameworks.base.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author gaopeng 2021/5/19
 */
@Slf4j
public class CustomSyncReadListener extends SyncReadListener {
    private boolean trace = false;
    private int count = 5000;

    public CustomSyncReadListener() {
    }

    public CustomSyncReadListener(boolean trace, int count) {
        this.trace = trace;
        this.count = count;
    }

    @Override
    public void invoke(Object object, AnalysisContext context) {
        super.invoke(object, context);
        if (trace && super.getList().size() % count == 0) {
            log.info("model read excel count: {}", super.getList().size());
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException e = (ExcelDataConvertException) exception;
            Field field = e.getExcelContentProperty().getField();
            String msg = String.format("第%d行第%d列格式不正确，Excel列名=%s，读取内容=%s，填充字段=%s, 填充类型=%s",
                    e.getRowIndex() + 1,
                    e.getColumnIndex() + 1,
                    getExcelName(field),
                    e.getCellData().getStringValue(),
                    field.getName(),
                    field.getType().getName());
            throw new CustomException(msg);
        }
        throw exception;
    }

    private String getExcelName(Field field) {
        ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
        return annotation != null ? Arrays.toString(annotation.value()) : null;
    }
}
